#include "TemperatureSensor.h"
#include "I2CManager.h"

#include <stdio.h>
#include <stdlib.h>

#define TEMPERATURE_REG 0x00
#define CONFIGURATION_REG 0x01
#define TEMP_HYSTERESIS_REG 0x02
#define TEMP_LIMIT_SET_REG 0x03


int getAmbientTemperature(int i2CFile, char address, float* temperature)
{
	u_int8_t upperHalf = 0;
	u_int8_t lowerHalf = 0;
	
	int val = 0;
	int coef = 1;
	int k = 0;
	
	if( read16(i2CFile, 0, address, TEMPERATURE_REG, &upperHalf, &lowerHalf) > 0)
	{
		/* Negative temperature */
		if( (upperHalf & 0x80) == 0x80 )
		{
			/* complement of each byte */
			upperHalf = ~upperHalf;
			lowerHalf = ~lowerHalf;
			
			coef = -1;
			/* add 1 to the end */
			k = 1;
		}
		
		val |= upperHalf << 8;
		val |= lowerHalf;
		*temperature = ( ((val >> 4) + k) * 0.0625 * coef);
		
		return 1;
	}
	
	return -1;
}

int setMaxAmbientTemperatureAlert(int i2CFile, char address, int value)
{
	return write8(i2CFile, 0, address, TEMP_LIMIT_SET_REG, value);
}

int setMinAmbientTemperatureAlert(int i2CFile, char address, int value)
{
	return write8(i2CFile, 0, address, TEMP_HYSTERESIS_REG, value);
}

int setTemperatureSensor(int i2CFile, char address, char mode)
{
	return write8(i2CFile, 0, address, CONFIGURATION_REG, mode);
}
